<!--
  - Copyright (C) 2024
  - All rights reserved, Designed By www.joolun.com
  - 注意：
  - 本软件为www.joolun.com开发研制，未经购买不得使用
  - 购买后可获得全部源代码（禁止转卖、分享、上传到码云、github等开源平台）
  - 一经发现盗用、分享等行为，将追究法律责任，后果自负
-->
<template>
	<view>
		<picker @change="changLang" :value="index" :range="picker" range-key="name">
			<view class="picker">
				<image src="/static/public/img/lang.png" style="width: 24px; height: 24px; opacity: 0.8;" />
			</view>
		</picker>
	</view>
</template>
<script>
/**
 * 国际化切换组件: 按照uniapp官方示例编写: https://ext.dcloud.net.cn/plugin?id=6462
 */
export default {
	data() {
		return {
			systemLocale: '',
			applicationLocale: 'zh-Hans',
			index: 0,
			isAndroid: false,
			picker: [
				{
					name: '中文',
					value: 'zh-Hans'
				},
				{
					name: 'English',
					value: 'en'
				}
			]
		};
	},
	created() {
		let applicationLocale = uni.getStorageSync('applicationLocale');
		if (applicationLocale) {
			this.applicationLocale = applicationLocale;
		} else {
			this.applicationLocale = uni.getLocale();
		}
		let systemInfo = uni.getSystemInfoSync();
		// this.systemLocale = systemInfo.language;
		this.isAndroid = systemInfo.platform.toLowerCase() === 'android';
		uni.onLocaleChange((e) => {
			this.applicationLocale = e.locale;
			this.index = this.picker.findIndex((item) => item.value == this.applicationLocale);
		});
		// 设置的语言回显
		if (this.applicationLocale) {
			this.index = this.picker.findIndex((item) => item.value == this.applicationLocale);
		}
	},
	methods: {
		changLang(e) {
			let index = e.detail.value;
			let langCode = this.picker[index].value;
			if (this.isAndroid) {
				uni.showModal({
					content: this.$t('commons.changeConfirm'),
					success: (res) => {
						if (res.confirm) {
							uni.setStorageSync('applicationLocale', langCode);
							uni.setLocale(langCode);
							this.$i18n.locale = langCode;
							//刷新页面
							// #ifdef H5
							location.reload();
							// #endif
							// #ifndef H5
							uni.reLaunch({
								url: '/pages/home/index'
							});
							// #endif
						}
					}
				});
			} else {
				uni.setStorageSync('applicationLocale', langCode);
				uni.setLocale(langCode);
				this.$i18n.locale = langCode;
				//刷新页面
				// #ifdef H5
				location.reload();
				// #endif
				// #ifndef H5
				// APP需要重启应用
				// #ifdef APP-PLUS
				plus.runtime.restart();
				// #endif
				uni.reLaunch({
					url: '/pages/home/index'
				});
				// #endif
			}
			// #ifdef MP
			// 小程序tabbar国际化
			uni.setTabBarItem({
				index: 0,
				text: this.$t('tabbar.tab1')
			});
			uni.setTabBarItem({
				index: 1,
				text: this.$t('tabbar.tab2')
			});
			uni.setTabBarItem({
				index: 2,
				text: this.$t('tabbar.tab3')
			});
			// #endif
		}
	}
};
</script>